package cn.edu.xhu.library_management.user.controller.Applets;

import cn.edu.xhu.library_management.common.entity.R;
import cn.edu.xhu.library_management.user.entity.LmUserOhter;
import cn.edu.xhu.library_management.user.entity.LmUserStudent;
import cn.edu.xhu.library_management.user.entity.LmUserTeacher;
import cn.edu.xhu.library_management.user.entity.dto.User;
import cn.edu.xhu.library_management.user.service.LmUserOhterService;
import cn.edu.xhu.library_management.user.service.LmUserStudentService;
import cn.edu.xhu.library_management.user.service.LmUserTeacherService;
import cn.edu.xhu.library_management.user.service.UserService;
import cn.edu.xhu.library_management.user.utils.*;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.concurrent.TimeUnit;

/**
 * @Author: MMJ
 * @Date: 2023 - 04 - 22
 * @Description: 小程序用户Controller
 */
@Api(tags = "小程序模块")
@ApiSort(4)
@RestController
@RequestMapping("/lm_user/user/applet")
public class UserController {

    @Autowired
    private LmUserOhterService otherService;
    @Autowired
    private LmUserStudentService studentService;
    @Autowired
    private LmUserTeacherService teacherService;
    @Autowired
    private UserService userService;
    @Autowired
    private SMSUtils smsUtils;
    @Autowired
    private SMSProperties prop;
    @Autowired
    private MinioUtils minioUtils;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("/register/{code}")
    @ApiOperation(value = "校外用户注册", produces = "application/json")
    @ApiOperationSupport(order = 420)
    public R addOtherUser(@RequestBody LmUserOhter userOther,@PathVariable("code")String code) {
        if (Boolean.FALSE.equals(redisTemplate.hasKey(prop.getPrefix() + "/code/register/" + userOther.getOthAccount()))){
            // 存在
            return R.error("验证码已经过期");
        }
        String redisCode = redisTemplate.opsForValue().get(prop.getPrefix() + "/code/register/" + userOther.getOthAccount());
        if (!code.equalsIgnoreCase(redisCode)){
            // 验证码不正确
            return R.error("验证码不正确");
        }
        boolean flag = otherService.addOtherUser(userOther);
        return flag ? R.ok("注册成功") : R.error("注册失败");
    }

    @PostMapping("/login")
    @ApiOperation(value = "用户登录", produces = "application/json")
    @ApiOperationSupport(order = 421)
    public R userLogin(@RequestBody User user) {
        //判断用户登录(校外11位 教师9位 学生12 - 19)
        User u = userService.login(user);

        // 存放 code 到 redis
//        redisTemplate.opsForValue().set("/smartLibrary/code", CodeUtil.fourCode());
        return u!=null?R.ok().data("user",u):R.error();
    }

    @GetMapping("/register/getSMSCode")
    @ApiOperation(value = "获取短信验证码", produces = "application/json")
    @ApiOperationSupport(order = 423)
    public R getSMSCode(String phone) {
        // 查询当前用户是否存在验证码
        if (Boolean.TRUE.equals(redisTemplate.hasKey(prop.getPrefix() + "/code/register/" + phone))){
            // 存在
            return R.error("请别重复点击");
        }
        String code = CodeUtil.fourCode();
        this.smsUtils.sendSMS(phone, code, this.prop.getSignName(), this.prop.getVerifyCodeTemplate());
        redisTemplate.opsForValue().set(prop.getPrefix()+"/code/register/"+phone,code,5, TimeUnit.MINUTES);
        return R.ok("验证码发送成功");
    }

    @PostMapping("/me/changeImg")
    @ApiOperation(value = "修改图片", produces = "application/json")
    @ApiOperationSupport(order = 424)
    public R changeImg(MultipartFile file,@RequestParam("account") String account) {
        int status = AccountUtils.getAccountType(account);
        String path = minioUtils.upload(file,"/WeChat-Applet/file/");
        switch (status){
            case 1:{
                // 学生
                LmUserStudent student = studentService.getById(account);
                if (student == null){
                    return R.error("无该学生");
                }
                if (student.getStImg() != null){
                    // 删除存在的照片
                    minioUtils.removeFile(student.getStImg(),"/WeChat-Applet/file/");
                }
                student.setStImg(path);
                studentService.updateById(student);
            }break;
            case 2:{
                // 教师
                LmUserTeacher teacher = teacherService.getById(account);
                if (teacher == null){
                    return R.error("无该教师");
                }
                if (teacher.getThImg() != null){
                    // 删除存在的照片
                    minioUtils.removeFile(teacher.getThImg(),"/WeChat-Applet/file/");
                }
                teacher.setThImg(path);
                teacherService.updateById(teacher);
            }break;
            case 3:{
                // 校外用户
                LmUserOhter other = otherService.getById(account);
                if (other == null) {
                    return R.error("无该用户");
                }
                if (other.getOthImg() != null){
                    // 删除存在的照片
                    minioUtils.removeFile(other.getOthImg(),"/WeChat-Applet/file/");
                }
                other.setOthImg(path);
                otherService.updateById(other);
            }break;
        }
        String filePath = path.substring(path.lastIndexOf("/"));
        return R.ok().data("imgUrl", "/file"+filePath);
    }
}
